﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using WebAPISelfHostDemo.Model;

namespace WebAPISelfHostDemo.Controller
{
    public class ProductsController : ApiController
    {
        private Product[] products = new Product[]
        {
            new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
            new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
            new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
        };

        public IEnumerable<Product> GetAllProducts()
        {
            Console.WriteLine("执行方法：GetAllProducts");
            return products;
        }

        public Product GetProductById(int id)
        {
            Console.WriteLine("执行方法：GetAllProductsById()");

            Product product = products.Where(p => p.Id == id).FirstOrDefault();
            if (product == null)
            {
                throw new HttpResponseException(System.Net.HttpStatusCode.NotFound);
            }
            return product;
        }

        public IEnumerable<Product> GetProductsByCategory(string category)
        {
            Console.WriteLine("执行方法：GetProductsByCategory()");

            return products.Where(p => string.Equals(p.Category, category, StringComparison.OrdinalIgnoreCase));
        }
    }
}